﻿using Mrsoft.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using MuYue.Common;
using MuYue.Http;

namespace Mrsoft.UI
{
    public partial class FrmLogin : Form
    {
        public FrmLogin() {
            InitializeComponent();
            btnLogin.Left = Width / 2 - btnLogin.Width / 2;
            //数据绑定
            _user.SetBind(txtUserName, "Text");
            _pass.SetBind(txtPassword, "Text");
            //圆角处理
            Mrsoft.Controls.ImageDrawing.BeSuittable(this);
            //皮肤背景加载
            MainPlugin.FrmSkinLoad(this, frmControl);
        }

        bool _logining;

        readonly Config<string> _user = new Config<string>(@".\common.cfg", "login/user", "");
        readonly Config<string> _pass = new Config<string>(@".\common.cfg", "login/pass", "");

        private void CloseWindow(object sender, EventArgs e) {
            this.Close();
        }

        private void WindowMinmized(object sender, EventArgs e) {
            WindowState = FormWindowState.Minimized;
        }

        private void cbxShowPassword_CheckedChanged(object sender, EventArgs e) {
            txtPassword.PasswordChar = cbxShowPassword.Checked ? '\0' : '*';
        }

        private void btnLogin_Click(object sender, EventArgs e) {
            if (!_logining) {
                _logining = true;
                new Task(Login).Start();
            }
        }

        /// <summary>
        ///异步登陆过程
        /// </summary>
        private void Login() {
            bool br = false;
            try {
                LoginUiUpdate("登陆中……");
                string password = Utility.Md5Encoding(_pass.Value);
                string url = string.Format("{2}api?user={0}&pass={1}&method=login&json=Y", _user.Value, password, Mrsoft.Properties.Resources.website);
                LoginResult.Set(url, _user.Value, password);
                if (!(br = LoginResult.Login)) {
                    MsgBox(LoginResult.FailReason + "!如有疑问请咨询漠然！", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
            }
            catch (Exception ex) {
                string msg = string.Format("连接服务器验证失败!请检查网络是否连接正常！\r\n{0}", ex.Message);
                MsgBox(msg, "登陆失败！", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
            if (br) {
                LoginUiUpdate("登陆成功...");
                Invoke((MethodInvoker)(Close));
                ConfigFactory.ClearDataBindings();
                return;
            }
            LoginUiUpdate("重新登陆");
            _logining = false;
        }

        private void MsgBox(string p1, string p2, MessageBoxButtons messageBoxButtons, MessageBoxIcon messageBoxIcon) {
            Invoke((MethodInvoker)delegate {
                MessageBox.Show(this, p1, p2, messageBoxButtons, messageBoxIcon);
            });
        }

        private void LoginUiUpdate(string p) {
            btnLogin.Invoke((MethodInvoker)delegate {
                btnLogin.Text = p;
                btnLogin.Update();
            });
        }

        frmPasswordChange _window;
        /// <summary>
        /// 修改账号密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnkChangePassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            if (_window == null)
                _window = new frmPasswordChange(_user, _pass);
            _window.ShowDialog(this);
        }

        /// <summary>
        /// 背景图像设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmControl_ClothBtnClick(object sender, EventArgs e) {
            MainPlugin.SetFrmSkin(this, this.frmControl);
        }

        private void linkRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            var url = "http://xiaolanchong.duapp.com/user/login.shtml";
            try {
                Process.Start(url);
            }
            catch {
                try { Process.Start("Chrome.exe", url); }
                catch { Process.Start("iexplore.exe", url); }
            }
        }

    }
}
